using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using PortugalPremiumRealEstate.BusinessEntities;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Drawing;
using OlympusSoftware.Technical.Globalize.BusinessLogic;

namespace PortugalPremiumRealEstate.Admin
{
    public partial class AddOpportunity : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Opportunity opp = null;
            if (!this.IsPostBack)
            {
                TurnDashBoardOn();

                if (Request["dbg"] != null)
                {
                    headerText.Text = "Titulo PT" + DateTime.Now.ToShortDateString() + DateTime.Now.ToShortTimeString() + DateTime.Now.Ticks.ToString();
                    headerTextEn.Text = "Titulo EN" + DateTime.Now.ToShortDateString() + DateTime.Now.ToShortTimeString() + DateTime.Now.Ticks.ToString();
                    description.Text = "Descricao PT" + DateTime.Now.ToShortDateString() + DateTime.Now.ToShortTimeString() + DateTime.Now.Ticks.ToString();
                    descriptionEn.Text = "Description EN" + DateTime.Now.ToShortDateString() + DateTime.Now.ToShortTimeString() + DateTime.Now.Ticks.ToString();
                }
                opp = GetOpportunity(false);
                Session["AddOpportunity"] = opp;
            }
            else 
            {
                opp = Session["AddOpportunity"] as Opportunity;
            }

            RenderOpportunitiesButtons(opp);
        }

        private void TurnDashBoardOn()
        {
            dashboardContainer.Visible = true;
            dashboardControlsContainer.Visible = false;
        }

        private void SwitchDashBoardVisibility()
        {
            dashboardContainer.Visible = !dashboardContainer.Visible;
            dashboardControlsContainer.Visible = !dashboardControlsContainer.Visible;
        }

        private void RenderOpportunitiesButtons(Opportunity opp)
        {
            if (opp != null && opp.Images != null)
            {
                foreach (SimpleImage si in opp.Images)
                {
                    CreateSimpleImageButton(si.Name);
                }
            }
        }

        private Opportunity GetOpportunity()
        {
            return GetOpportunity(true);
        }

        private Opportunity GetOpportunity(bool loadFromMemory)
        {
            Opportunity opp = Session["AddOpportunity"] as Opportunity;
            if (opp == null)
                opp = new Opportunity();

            if (loadFromMemory)
            {
                return opp;
            }

            opp.Title = headerText.Text;
            opp.TitleEn = headerTextEn.Text;
            opp.Description = description.Text;
            opp.DescriptionEn = descriptionEn.Text;

            return opp;
        }

        private Opportunity SaveSimpleImageInOpportunity(SimpleImage si, Opportunity opp)
        {
            return SaveSimpleImageInOpportunity(si, opp, true);
        }

        private Opportunity SaveSimpleImageInOpportunity(SimpleImage si, Opportunity opp, bool updateInMemory)
        {
            opp.Title = headerText.Text;
            opp.TitleEn = headerTextEn.Text;
            opp.Description = description.Text;
            opp.DescriptionEn = descriptionEn.Text;

            int iNumImgs = int.Parse(numImgs.Value);

            if (opp.Images == null)
                opp.Images = new System.Collections.Generic.List<SimpleImage>();

            if (!String.IsNullOrEmpty(si.Name) && si.Contents != null && si.Contents.Length > 0)
            {
                if (opp.Id != null)
                {
                    opp.Images.Add(new SimpleImage(si.Name, si.Contents, opp.Id.Value));
                }
                else 
                {
                    opp.Images.Add(new SimpleImage(si.Name, si.Contents));
                }
            }

            if (updateInMemory)
                Session["AddOpportunity"] = opp;

            return opp;
        }
        
        protected void btnAddMoreImgs_Click(object sender, EventArgs e)
        {
            try
            {
                if (imageUpload != null && !String.IsNullOrEmpty(imageUpload.FileName) && imageUpload.FileBytes != null && imageUpload.FileBytes.Length > 0)
                {
                    SaveSimpleImageInOpportunity(new SimpleImage(imageUpload.FileName, imageUpload.FileBytes), GetOpportunity());
                    CreateSimpleImageButton(imageUpload.FileName);
                    msg.ForeColor = Color.Green;
                    msg.Text += Environment.NewLine + "Imagem "+imageUpload.FileName+" guardada com sucesso!";
                }
            }
            catch (Exception ex)
            {
                msg.ForeColor = Color.Red;
                msg.Text += Environment.NewLine + Environment.NewLine + "Ups. Ocorreu um problema. Detalhes: " + ex.Message;
                return;
            }
            
        }

        private void CreateSimpleImageButton(string simpleImageName)
        {
            Button btnRemoveImg = new Button();
            btnRemoveImg.ID = simpleImageName;
            btnRemoveImg.Click += new EventHandler(btnRemoveImg_Click);
            btnRemoveImg.Text = simpleImageName;
            imagesPreviewContainer.Controls.Add(btnRemoveImg);
        }

        void btnRemoveImg_Click(object sender, EventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                btn.Visible = false;

                Opportunity opp = Session["AddOpportunity"] as Opportunity;
                opp.Images.Remove(opp.Images.Find(delegate(SimpleImage match) { return match.Name == btn.ID; }));

                msg.ForeColor = Color.Green;
                msg.Text += Environment.NewLine + "A imagem " + btn.Text + " foi removida com sucesso";

                Session["AddOpportunity"] = opp;
            }
            catch (Exception ex)
            {
                msg.ForeColor = Color.Red;
                msg.Text += Environment.NewLine + "Ups. Ocorreu um problemaa o remover a imagem. Detalhes: " + ex.Message;
                return;
            }
        }

        protected void btnInsertOpportunity_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.Page.IsValid)
                {
                    Opportunity newOpp = GetOpportunity(true);

                    Database database = DatabaseFactory.CreateDatabase("OlympusSoftware");
                    int newOppId = SaveOpportunityDb(newOpp, database);
                    newOpp.Id = newOppId;
                    foreach (SimpleImage si in newOpp.Images)
                    {
                        if (si != null && si.Contents != null && si.Contents.Length > 0)
                        {
                            SaveOpportunityImagesDb(newOpp.Id.Value, si, database);
                        }
                    }
                    msg.ForeColor = Color.Green;
                    msg.Text += Environment.NewLine + "Foi criada a oportunidade " + newOppId.ToString() +" com sucesso!";
                }
            }
            catch (Exception ex) 
            {
                msg.ForeColor = Color.Red;
                msg.Text += Environment.NewLine + "Ups. Ocorreu um problema. Detalhes: "+ex.Message;
                return;
            }
        }

        private static int SaveOpportunityDb(Opportunity newOpp, Database database)
        {
            DbCommand storedProcCommand = database.GetStoredProcCommand("[dbo].[AddOpportunity]");
            database.AddInParameter(storedProcCommand, "@title", DbType.String, newOpp.Title);
            database.AddInParameter(storedProcCommand, "@titleEn", DbType.String, newOpp.TitleEn);
            database.AddInParameter(storedProcCommand, "@description", DbType.String, newOpp.Description);
            database.AddInParameter(storedProcCommand, "@descriptionEn", DbType.String, newOpp.DescriptionEn);

            int newOppId = -1;
            using (IDataReader reader = database.ExecuteReader(storedProcCommand))
            {
                while (reader.Read())
                {
                    newOppId = reader.GetInt32(0);
                }
            }

            return newOppId;
        }

        private static int SaveOpportunityImagesDb(int opportunityId, SimpleImage si, Database database)
        {
            DbCommand storedProcCommand = database.GetStoredProcCommand("[dbo].[AddOpportunityImage]");
            database.AddInParameter(storedProcCommand, "@opportunityId", DbType.Int32, opportunityId);
            database.AddInParameter(storedProcCommand, "@name", DbType.String, si.Name);
            database.AddInParameter(storedProcCommand, "@contents", DbType.Binary, si.Contents);
            
            int newImgId = -1;
            using (IDataReader reader = database.ExecuteReader(storedProcCommand))
            {
                while (reader.Read())
                {
                    newImgId = reader.GetInt32(0);
                }
            }

            return newImgId;
        }

        private static Database GetDatabase()
        {
            return DatabaseFactory.CreateDatabase("OlympusSoftware");
        }

        protected void btnLimpar_Click(object sender, EventArgs e)
        {
            ClearAll();
        }

        private void ClearAll()
        {
            Session["AddOpportunity"] = null;
            headerText.Text = headerTextEn.Text = description.Text = descriptionEn.Text = msg.Text = String.Empty;
            imagesPreviewContainer.Controls.Clear();
        }

        protected void LoadIdBtn_Click(object sender, EventArgs e)
        {
            ClearAll();

            Opportunity opp = new Opportunity();

            string rOppid = txtOppId.Text;
            if (String.IsNullOrEmpty(rOppid))
            {
                return;
            }

            int oppId = int.Parse(rOppid);

            GlobalizeManager gm = base.Application["GlobalizeManager"] as GlobalizeManager;
            Database database = GetDatabase();
            DbCommand storedProcCommand = database.GetStoredProcCommand("[dbo].[GetOpportunity]");
            database.AddInParameter(storedProcCommand, "@oppId", DbType.Int32, oppId);

            int lastOppId = -1;
            using (IDataReader reader = database.ExecuteReader(storedProcCommand))
            {
                while (reader.Read())
                {
                    if (lastOppId != reader.GetInt32(0))
                    {
                        opp.Id = reader.GetInt32(0);
                        opp.Title = gm.GlobalizeProvider.GetText(1, 2, 2, reader.GetInt32(1));
                        opp.TitleInfoId = reader.GetInt32(1);
                        opp.TitleEn = gm.GlobalizeProvider.GetText(1, 2, 1, reader.GetInt32(1));
                        opp.TitleEnInfoId = reader.GetInt32(1);
                        opp.Description = gm.GlobalizeProvider.GetText(1, 2, 2, reader.GetInt32(2));
                        opp.DescriptionInfoId = reader.GetInt32(2);
                        opp.DescriptionEn = gm.GlobalizeProvider.GetText(1, 2, 1, reader.GetInt32(2));
                        opp.DescriptionEnInfoId = reader.GetInt32(2);
                    }

                    if (opp.Images == null)
                        opp.Images = new System.Collections.Generic.List<SimpleImage>();

                    if (!reader.IsDBNull(6) && !reader.IsDBNull(7))
                    {
                        opp.Images.Add(new SimpleImage(reader.GetString(6), reader.GetValue(7) as Byte[], reader.GetInt32(5)));
                    }
                }
            }

            headerText.Text = opp.Title;
            headerTextEn.Text = opp.TitleEn;
            description.Text = opp.Description;
            descriptionEn.Text = opp.DescriptionEn;

            RenderOpportunitiesButtons(opp);

            Session["AddOpportunity"] = opp;

            editLoadControlsContainer.Visible = false;
            opportunityControlsContainer.Visible = true;
        }

        protected void btnEditOpportunity_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.Page.IsValid)
                {
                    Opportunity newOpp = GetOpportunity(false);
                    Database database = GetDatabase();
                    EditOpportunityDb(newOpp, database);
                    foreach (SimpleImage si in newOpp.Images)
                    {
                        if (si != null && si.Contents != null && si.Contents.Length > 0)
                        {
                            SaveOpportunityImagesDb(newOpp.Id.Value, si, database);
                        }
                    }
                    msg.ForeColor = Color.Green;
                    msg.Text += Environment.NewLine + "Foi editada a oportunidade " + newOpp.Id.Value.ToString() + " com sucesso!";
                }
            }
            catch (Exception ex)
            {
                msg.ForeColor = Color.Red;
                msg.Text += Environment.NewLine + "Ups. Ocorreu um problema. Detalhes: " + ex.Message;
                return;
            }
        }

        private void EditOpportunityImageDb(int? oppId, SimpleImage si, Database database)
        {
            if (si != null && si.Id == null && oppId!=null)
            {
                SaveOpportunityImagesDb(oppId.Value, si, database);
                return;
            }

            DbCommand storedProcCommand = database.GetStoredProcCommand("[dbo].[EditOpportunityImage]");
            database.AddInParameter(storedProcCommand, "@id", DbType.Int32, si.Id.Value);
            database.AddInParameter(storedProcCommand, "@name", DbType.String, si.Name);
            database.AddInParameter(storedProcCommand, "@contents", DbType.Binary, si.Contents);
            database.ExecuteReader(storedProcCommand);
        }

        private void EditOpportunityDb(Opportunity opp, Database database)
        {
            DbCommand storedProcCommand = database.GetStoredProcCommand("[dbo].[EditOpportunity]");
            database.AddInParameter(storedProcCommand, "@oppId", DbType.Int32, opp.Id.Value);
            database.AddInParameter(storedProcCommand, "@title", DbType.String, opp.Title);
            database.AddInParameter(storedProcCommand, "@titleInfoId", DbType.Int32, opp.TitleInfoId);
            database.AddInParameter(storedProcCommand, "@titleEn", DbType.String, opp.TitleEn);
            database.AddInParameter(storedProcCommand, "@titleInfoEnId", DbType.Int32, opp.TitleEnInfoId);
            database.AddInParameter(storedProcCommand, "@description", DbType.String, opp.Description);
            database.AddInParameter(storedProcCommand, "@descriptionInfoId", DbType.Int32, opp.DescriptionInfoId);
            database.AddInParameter(storedProcCommand, "@descriptionEn", DbType.String, opp.DescriptionEn);
            database.AddInParameter(storedProcCommand, "@descriptionEnId", DbType.Int32, opp.DescriptionEnInfoId);
            database.ExecuteReader(storedProcCommand);
        }

        protected void dashboardAddOpp_Click(object sender, EventArgs e)
        {
            SwitchDashBoardVisibility();
            btnInsertOpportunity.Visible = true;
            btnEditOpportunity.Visible = false;
            editLoadControlsContainer.Visible = false;
            opportunityControlsContainer.Visible = true;
            msg.Text = string.Empty;
        }

        protected void dashboardEditOpp_Click(object sender, EventArgs e)
        {
            SwitchDashBoardVisibility();
            btnInsertOpportunity.Visible = false;
            btnEditOpportunity.Visible = true;
            editLoadControlsContainer.Visible = true;
            opportunityControlsContainer.Visible = false;
            msg.Text = string.Empty;
        }

        protected void btnBackDashBoard_Click(object sender, EventArgs e)
        {
            SwitchDashBoardVisibility();
            btnInsertOpportunity.Visible = false;
            btnEditOpportunity.Visible = false;
            editLoadControlsContainer.Visible = false;
            opportunityControlsContainer.Visible = false;
            ClearAll();
            Session["AddOpportunity"] = null;
        }


    }
}
